import wepy from 'wepy'

export default class extends wepy.mixin {
  data = {
    // 商品详情数据
    goodsInfo: {},
    // 地址
    address: null
  }
  // 页面加载事件
  onLoad(options) {
    console.log(options)
    this.getGoodsDetail(options.goods_id)
  }

  // 获取商品详细信息
  async getGoodsDetail(id) {
    const {data: res} = await wepy.get('/goods/detail?goods_id=' + id)
    if (res.meta.status !== 200) {
      return wepy.baseToast()
    }
    console.log(res)
    // 将图片格式转化为jpg格式
    res.message.goods_introduce = res.message.goods_introduce.replace(/.webp/, '.jpg')
    this.goodsInfo = res.message
    // 强制渲染
    this.$apply()
  }

  computed = {
    goods_address() {
      if (this.address === null) {
        return '请添加收货地址'
      }
      const { cityName, provinceName, countyName, detailInfo } = this.address
      return provinceName + cityName + countyName + detailInfo
    }
  }

  methods = {
    // 添加地址
    async toAddAdress() {
      const res = await wepy.chooseAddress().catch(res => {
        return res
      })
      console.log(res)
      if (res.errMsg !== 'chooseAddress:ok') {
        return wepy.baseToast()
      }
      this.address = res
      // 强制渲染
      this.$apply()
    },

    // 图片预览
    imgPreview(current) {
      wepy.previewImage({
        urls: this.goodsInfo.pics.map(res => res.pics_big),
        current: current
      })
    },

    // 添加购物车
    onClickButton() {
      // 将数据存储到全局cart当中
      // 获取全局商品数据
      this.$parent.saveGoodsItem(this.goodsInfo)
      wepy.showToast({
        title: '添加商品成功',
        icon: 'success'
      })
    }
  }
}
